<template>
  <div class="messBord">
    <div class="tools">
      <Search
        @toSearch="toSearch"
        :placeholder1="placeholder1"
        @reFresh="initList"
      ></Search>
    </div>
    <router-view @reFresh="initList"></router-view>
    <Table
      v-if="refresh"
      :list-data="List"
      @reFresh="initList"
      @sortChange="sortChange"
      @delete="deleteRow"
    >
      <template #column>
        <el-table-column
          prop="mess_author"
          label="留言者"
          min-width="180"
          align="center"
        >
          <template #default="scope">
            <span class="avatar">
              <img :src="scope.row.mess_avatarUrl" />
            </span>
            <span class="userName">{{ scope.row.mess_author }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="mess_content"
          label="留言内容"
          min-width="250"
          align="center"
        >
        </el-table-column>

        <el-table-column
          label="显示状态"
          min-width="180"
          align="center"
          :filters="[
            { text: '已显示', value: 1 },
            { text: '未显示', value: 0 },
          ]"
          :filter-multiple="false"
          :filter-method="filterTag"
          filter-placement="bottom-end"
        >
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.mess_status == 1">
              <span>已显示</span>
            </el-tag>
            <el-tag type="danger" v-else>
              <span>未显示</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="公告层级" min-width="100" align="center">
          <template #default="scope">
            <el-tag>
              <span v-if="scope.row.mess_index == 1">置顶</span>
              <span v-else>{{ scope.row.mess_index || "未设置 " }}</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="mess_date"
          sortable="custom"
          label="留言日期"
          min-width="160"
          align="center"
          column-key="id"
        />
        <el-table-column
          label="操作"
          header-align="center"
          align="center"
          min-width="220"
        >
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
              >层级</el-button
            >
            <el-button
              v-if="scope.row.mess_status === 0"
              size="small"
              type="primary"
              @click="changeStatus(scope.$index, scope.row)"
              >发布</el-button
            >
            <el-button
              v-else
              size="small"
              type="warning"
              @click="down(scope.$index, scope.row)"
              >关闭</el-button
            >
            <el-button
              size="small"
              type="danger"
              @click="deleteRow(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </template>
    </Table>
    <div style="height: 50px">
      <Pagination
        :lockNxt="lockNxt"
        @prePage="prePage"
        @nxtPage="nxtPage"
      ></Pagination>
    </div>
  </div>
</template>

<script lang="ts">
import { nextTick, ref, Ref, watch } from "vue";
import { MessBord } from "../types/listTypes";
import type { TableColumnCtx } from "element-plus/es/components/table/src/table-column/defaults";
import { ElMessage, ElMessageBox } from "element-plus";
import router from "../router/index";
import request from "../axios/index";
import Search from "../components/Search.vue";
import Table from "../components/Table.vue";
import Pagination from "../components/Pagination.vue";
import { timeFormat } from "../utils/dateFormat";

export default {
  name: "messBord",
  components: {
    Search,
    Table,
    Pagination,
  },
  setup() {
    //控制刷新显示
    let refresh: Ref<boolean> = ref(true);
    //刷新触发函数
    function toFresh() {
      refresh.value = false;
      nextTick(() => {
        refresh.value = true;
      });
    }
    //监听日期排序触发
    function sortChange(order: string) {
      switch (order) {
        case "ascending":
          getListByAsc(pageCount.value, 1);
          break;
        case "descending":
          getList(pageCount.value, 1);
          break;
        default:
          getListByAsc(pageCount.value, 1);
          break;
      }
    }
    //初始化组件内容
    const placeholder1: string = "请输入留言内容";

    //初始化公告列表
    let List: Ref<MessBord[]> = ref([]);

    //初始化列表请求
    function initList(pc: number) {
      pageCount.value = pc;
      getList();
    }
    //初始化公告列表请求
    function getList(count: number = pageCount.value, page: number = 1) {
      request
        .get("/admin/messBord/messList", {
          params: {
            count: count,
            page: page,
          },
        })
        .then((res) => {
          List.value = timeFormat(res.data.data, "mess_date");
        });
    }
    //获取公告列表(升序)
    function getListByAsc(pageCount: number = 3, page: number = 1) {
      request
        .get("/admin/messBord/messListByAsc", {
          params: {
            count: pageCount,
            page: page,
          },
        })
        .then((res) => {
          List.value = timeFormat(res.data.data, "mess_date");
          ElMessage({
            message: res.data.message,
            type: "success",
          });
        });
    }
    //处理状态筛选
    const filterTag = (value: number, row: MessBord) => {
      return row.mess_status === value;
    };
    const filterHandler = (
      value: string,
      row: MessBord,
      column: TableColumnCtx<MessBord>
    ) => {
      const property = column["property"];
      return row[property] === value;
    };
    //表格层级按钮
    function handleEdit(index, row) {
      router.push({
        path: "/smart-e/admin/index/messBord/ChangeIndex",
        query: {
          id: row.id,
          index: row.mess_index,
        },
      });
    }
    //修改状态
    function changeStatus(index, row) {
      ElMessageBox.confirm("是否确认显示该公告留言")
        .then(() => {
          request
            .post("/admin/messBord/changeStatus", {
              messId: row.id,
              messStatus: 1,
            })
            .then((res) => {
              if (res.data.code === 200) {
                ElMessage({
                  message: res.data.message,
                  type: "success",
                });
                toFresh();
              } else {
                ElMessage({
                  message: res.data.message,
                  type: "error",
                });
              }
            });
        })
        .catch((err) => {
          ElMessage("已取消显示");
        });
    }
    //关闭
    function down(index, row) {
      ElMessageBox.confirm("是否确认关闭该公共留言")
        .then(() => {
          request
            .post("/admin/messBord/changeStatus", {
              messId: row.id,
              messStatus: 0,
            })
            .then((res) => {
              if (res.data.code === 200) {
                ElMessage({
                  message: res.data.message,
                  type: "success",
                });
                toFresh();
              } else {
                ElMessage({
                  message: res.data.message,
                  type: "error",
                });
              }
            });
        })
        .catch((err) => {
          ElMessage("已取消关闭");
        });
    }
    //表格删除按钮
    function deleteRow(index, row) {
      ElMessageBox.confirm("是否确认删除该公共留言")
        .then(() => {
          request
            .post("/admin/messBord/deleteMess", {
              messId: row.id,
            })
            .then((res) => {
              if (res.data.code === 200) {
                ElMessage({
                  message: res.data.message,
                  type: "success",
                });
                toFresh();
              } else {
                ElMessage({
                  message: res.data.message,
                  type: "error",
                });
              }
            });
        })
        .catch((err) => {
          ElMessage("已取消删除");
        });
    }
    //发起搜索请求
    async function toSearch(input) {
      try {
        const res = await request.get(
          "/admin/messBord/searchMessBord_content",
          {
            params: {
              keywords: input.keyWords,
            },
          }
        );
        List.value = timeFormat(res.data.data, "mess_date");
      } catch (e) {
        console.error(e);
      }
    }

    //分页
    //定义单页数量
    let pageCount: Ref<number> = ref(0);
    //定义锁定下页
    let lockNxt: Ref<boolean> = ref(false);
    //触发上一页
    function prePage(currentPage: number) {
      ElMessage(`第${currentPage}页`);
      getList(pageCount.value, currentPage);
    }
    //触发下一页
    function nxtPage(currentPage: number) {
      ElMessage(`第${currentPage}页`);
      getList(pageCount.value, currentPage);
    }
    //监听页面长度
    watch(
      () => List.value.length,
      (newVal, oldVal) => {
        if (newVal < pageCount.value) {
          lockNxt.value = true;
        } else {
          lockNxt.value = false;
        }
      },
      {
        immediate: true,
      }
    );

    return {
      refresh,
      placeholder1,
      List,
      getList,
      getListByAsc,
      sortChange,
      filterTag,
      filterHandler,
      deleteRow,
      toSearch,
      handleEdit,
      changeStatus,
      down,
      prePage,
      nxtPage,
      initList,
      lockNxt,
    };
  },
};
</script>

<style scoped>
.messBord {
  position: relative;
  width: 98%;
  min-height: 520px;
  background-color: #fff;
}
.tools {
  width: 100%;
  height: 50px;
  overflow: hidden;
}
.avatar img {
  width: 30px;
  height: 30px;
  border-radius: 50%;
}
.userName {
  display: block;
  float: right;
  width: 70px;
  height: 30px;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
